package org.example.spring_boot_blog.common.utils;

import io.jsonwebtoken.*;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.io.Encoders;
import io.jsonwebtoken.security.Keys;
import io.jsonwebtoken.security.SignatureException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.crypto.SecretKey;
import java.security.Key;
import java.util.Date;
import java.util.Map;
@Slf4j
public class JwtUtil {
    private static final String secret="ReACVyvCMLBkQ620fhWaFqbxQNXpfN1e0A3A5LOOT6I=";
    private static final Key key= Keys.hmacShaKeyFor(Decoders.BASE64.decode(secret));
    private static final long expriation=24*60*60*1000;
    //生成token
    public static String genToken(Map<String,Object> map) {
        return Jwts.builder()
                .setClaims(map)
//                .setSubject()
                .signWith(key)
                .setExpiration(new Date(System.currentTimeMillis()+expriation))
                .setIssuedAt(new Date())
                .compact();
    }
//检验token
    public static Claims parseToken(String token){
        if(!StringUtils.hasLength(token)){
            return null;
        }

        JwtParser build = Jwts.parserBuilder().setSigningKey(key).build();
        Claims body=null;
        try {
            body = build.parseClaimsJws(token).getBody();
            return body;

        }catch (ExpiredJwtException e){
           log.error("token过期了，token:{}",token);
        }catch (SignatureException e){
            log.error("签名错误，token:{}",token);
        }catch (Exception e){
            log.error("token无效，token:{}",token);
        }

        return null;
    }
    //生成密钥
    public void genKey(){
        SecretKey secretKey = Keys.secretKeyFor(SignatureAlgorithm.HS256);
        String encode = Encoders.BASE64.encode(secretKey.getEncoded());
        System.out.println(encode);
    }
}
